from django import forms
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm, PasswordResetForm
from django.contrib.auth.models import User

from captcha.fields import CaptchaField

from .models import Profile


class LoginForm(AuthenticationForm):
    """
    用户登录表单
    """
    remember_me = forms.BooleanField(label='下次自动登录', initial=False, required=False)


class RegistrationForm(UserCreationForm):
    """
    新用户注册表单
    """

    email = forms.EmailField(help_text="用于帐号认证和密码重置")
    captcha = CaptchaField()

    def clean_email(self):
        """
        确保注册邮箱的唯一性
        """
        value = self.cleaned_data['email']
        qs = User.objects.filter(email__iexact=value)
        if not qs.exists():
            return value
        raise forms.ValidationError("邮箱地址已被注册，请换一个")


class ResetForm(PasswordResetForm):
    """
    登录密码重置表单
    """

    email = forms.EmailField(help_text="帐号注册邮箱地址")
    captcha = CaptchaField()

    def clean_email(self):
        """
        验证邮箱地址是否有效
        """
        try:
            self.user = User.objects.get(email=self.cleaned_data['email'], is_active=True)
        except User.DoesNotExist:
            raise forms.ValidationError("没有与邮箱地址相匹配的帐号")


class ProfileForm(forms.ModelForm):
    """
    用户资料编辑表单
    """

    email = forms.EmailField(help_text="用于帐号认证和密码重置")

    class Meta:
        model = Profile
        fields = ('email', 'birthday', 'location', 'website', 'bio')


class ChangePasswordForm(forms.ModelForm):
    """
    更改密码表单
    """

    id = forms.CharField(widget=forms.HiddenInput())
    old_password = forms.CharField(widget=forms.PasswordInput(),
        label='当前密码',
        required=True)

    new_password = forms.CharField(widget=forms.PasswordInput(),
        label='新密码',
        required=True)
    confirm_password = forms.CharField(widget=forms.PasswordInput(),
        label='确认新密码',
        required=True)

    class Meta:
        model = User
        fields = ['id', 'old_password', 'new_password', 'confirm_password']

    def clean(self):
        super(ChangePasswordForm, self).clean()
        old_password = self.cleaned_data.get('old_password')
        new_password = self.cleaned_data.get('new_password')
        confirm_password = self.cleaned_data.get('confirm_password')
        id = self.cleaned_data.get('id')
        user = User.objects.get(pk=id)
        if not user.check_password(old_password):
            self._errors['old_password'] = self.error_class(['当前密码不正确。请重试。如果忘记了密码，可以“重置密码”'])
        if new_password and new_password != confirm_password:
            self._errors['new_password'] = self.error_class(['新密码两次输入不匹配'])
        return self.cleaned_data
